package logic

import (
	"github.com/zachary/tbox/internal/model"
	"github.com/zachary/tbox/internal/svc"
	"github.com/zachary/tbox/internal/types"
)

type StuLogic struct {
}

func NewStuLogic() *StuLogic {
	return &StuLogic{}
}

func (l *StuLogic) Add(v *types.StudentAddReq) (*model.StudentModel, error) {
	stu := model.StudentModel{Name: v.Name, Sex: v.Sex, Age: v.Age, Address: v.Address}
	result := svc.Db().Create(&stu)
	if result.Error != nil {
		return nil, result.Error
	}
	return &stu, nil
}

func (l *StuLogic) List(v *types.StudentSearchReq) ([]model.StudentModel, error) {
	var stus []model.StudentModel
	where := model.StudentModel{Name: v.Name, Sex: v.Sex, Age: v.Age}
	result := svc.Db().
		Where(where).
		Order("created_at desc").
		Find(&stus)
	if result.Error != nil {
		return nil, result.Error
	}
	return stus, nil
}

func (l *StuLogic) Edit(v *types.StudentEditReq) error {
	stu := model.StudentModel{Name: v.Name, Sex: v.Sex, Age: v.Age, Address: v.Address}
	result := svc.Db().Model(&model.StudentModel{BaseModel: model.BaseModel{ID: v.Id}}).Updates(stu)
	return result.Error
}
